package com.cyw.common.utils;

import com.cyw.common.config.trace.TraceIdGenerator;
import com.cyw.common.constants.CommonConstant;
import com.cyw.common.exceptions.BaseException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

/**
 * @author sxw
 * @date 2018-03-07 11:54
 */
public class LogUtils {

    /**
     * 打印异常:错误级别
     * @param t
     */
    public static void printError(Throwable t) {
        printError(t, "未知错误");
    }

    /**
     * 打印异常:错误级别
     * @param t
     * @param msg
     */
    public static void printError(Throwable t, String msg) {
        getErrorLogger().error("{}:{}", msg, ExceptionUtils.getFullStackTrace(t));
    }

    /**
     * 打印异常:警告级别
     * @param t
     */
    public static void printWarn(Throwable t) {
        printWarn(t, "");
    }

    /**
     * 打印异常:警告级别
     * @param t
     * @param msg
     */
    public static void printWarn(Throwable t, String msg) {
        getInfoLogger().warn("{}:{}", msg, adaptMessage(t));
    }

    /**
     * 打印异常:信息级别
     * @param t
     */
    public static void printInfo(Throwable t) {
        printInfo(t, "");
    }

    /**
     * 打印异常:信息级别
     * @param t
     * @param msg
     */
    public static void printInfo(Throwable t, String msg) {
        getInfoLogger().info("{}:{}", msg, adaptMessage(t));
    }

    /**
     * 如果是业务异常就获取堆栈
     *
     * @param t
     * @return
     */
    private static String adaptMessage(Throwable t) {
        return t instanceof BaseException ? ExceptionUtils.getFullStackTrace(t) : t.getMessage();
    }

    /**
     * 日志增加新的traceId
     */
    public static void putTraceId(){
        putTraceId(null);
    }

    /**
     * 日志增加traceId
     * @param traceId 获取到的traceId
     */
    public static void putTraceId(String traceId){
        if (StringUtils.isBlank(traceId)){
            traceId = TraceIdGenerator.traceId();
        }
        MDC.put(CommonConstant.traceIdKey, traceId);
    }

    /**
     * 清除traceId
     */
    public static void clearTraceId(){
        MDC.remove(CommonConstant.traceIdKey);
    }

    /** 获取日志logger，使用该loggger打印的日志会输出到统一的日志文件 **/
    public static Logger getErrorLogger() {
        return LoggerFactory.getLogger("error_log");
    }

    public static Logger getInfoLogger() {
        return LoggerFactory.getLogger("info_log");
    }

    public static Logger getThirdpartLogger() {
        return LoggerFactory.getLogger("thirdpart_log");
    }

    public static Logger getMQLogger() {
        return LoggerFactory.getLogger("mq_log");
    }

    public static Logger getScheduleLogger() {
        return LoggerFactory.getLogger("schedule_log");
    }

    public static Logger getAccessLogger() {
        return LoggerFactory.getLogger("access_log");
    }
    /** 获取日志logger，使用该loggger打印的日志会输出到统一的日志文件 **/
}
